package com.campus.controller.user;

import com.campus.constant.JwtClaimsConstant;
import com.campus.constant.MessageConstant;
import com.campus.dto.UserLoginDTO;
import com.campus.dto.UserRegisterDTO;
import com.campus.entity.User;
import com.campus.properties.JwtProperties;
import com.campus.result.Result;
import com.campus.service.UserService;
import com.campus.utils.JwtUtil;
import com.campus.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author TaiZai
 * @data 2024/10/21 17:21
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    // 短信验证码key
    private static final String PHONE_CODE_KEY = "phone_code_:";

    /**
     * 用户登录账号密码
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {

        User user = userService.login(userLoginDTO);

        // 登陆成功，生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );

        // 构造返回数据
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .imgUrl(user.getImgUrl())
                .roleId(user.getRoleId())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    /**
     * 发送登录短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/send-login-code")
    public Result<String> SendPhoneCode(@RequestParam String phone) {
        userService.sendLoginCode(phone);
        return Result.success(MessageConstant.PHONE_CODE_SUCCESS);
    }

    /**
     * 发送注册验证码
     * @param
     * @return
     */
    @GetMapping("/send-register-code")
    public Result<String> SendRegisterCode(@RequestParam String phone) {
        userService.sendRegisterCode(phone);
        return Result.success(MessageConstant.PHONE_CODE_SUCCESS);
    }


    @PostMapping("/register")
    public Result<String> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        userService.register(userRegisterDTO);
        return Result.success(MessageConstant.REGISTER_SUCCESS);
    }
}
